<?php
/**
 * Created by PhpStorm.
 * User: js
 * Date: 2018/9/30
 * Time: 15:37
 */

namespace app\modules\mch\models;
use app\models\Agent;


class AgentForm extends Model
{
    public $store_id;
    public $model;//?
    public $account;
    public $pwd;
    public $state;


    public function rules()
    {
        return [
            [['account','pwd'],'trim'],
            [['account','pwd'],'string'],
            [['account','pwd','state','store_id'],'required','on'=>'edit'],
            [['state'],'in','range'=>[0,1]],
        ];
    }

    public function attributeLabels()
    {
        return [
            'account'=>'账号',
            'pwd'=>'密码',
            'state'=>'状态',
            'store_id'=>'店铺id',
        ];
    }
    public function save()
    {
        if(!$this->validate()){
            return $this->getModelError();
        }

        if($this->model->isNewRecord){
            $this->model->is_delete = 0;
            $this->model->create_time = time();
        }
        if($this->account != $this->model->account){
            $exit = Agent::find()->where(['account'=>$this->account,'is_delete'=>0])->exists();
            if($exit){
                return [
                    'code'=>1,
                    'msg'=>'该账号名已存在'
                ];
            }
        }

        $this->model->store_id = $this->store_id;
        $this->model->account = $this->account;
        $this->model->pwd  = $this->pwd;
        $this->model->state = $this->state;

        if($this->model->save()){
            return [
                'code'=>0,
                'msg'=>'成功'
            ];
        }else{
            return $this->getModelError($this->model);
        }
    }
}